package com.hao.nettyrpc.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author haoge
 * @version 1.0
 * @date 2023/4/12 11:02
 *
 * 单例工厂
 */
public class SingletonFactory {
    private static Map<Class,Object> objectMap = new HashMap<>();

    private SingletonFactory(){}

    public static <T> T getInstance(Class<T> clazz) {
        Object instance = objectMap.get(clazz);
        if (instance == null) {
            synchronized (clazz) {

                if (instance == null) {
                    try {
                        instance = clazz.newInstance();
                        objectMap.put(clazz,instance);
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            }
        }

        return clazz.cast(instance);
    }
 }
